#include "net.h"


/* 服务器 */
int main()
{
	int fd = -1;
	struct sockaddr_in soc;

	//创建套接字
	if( (fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
	{
		perror("socket");
		exit(0);
	}

	/* 填充结构体 */
	soc.sin_family = AF_INET;
	soc.sin_port = htons(PORT);
#if 1
	/* 只适合ipv4 */
	soc.sin_addr.s_addr = inet_addr(IPV4_ADDR);

#else
	/* ipv4 和 ipv6*/
	if( (inet_pton(AF_INET, IPV4_ADDR, (void*)&soc.sin_addr)) < 0)
	{
		perror(pton);
		exit(0);
	}

#endif
	/* 绑定 */
	if( (bind(fd, (struct sockaddr* )&soc, sizeof(soc) )) < 0)
	{
		perror("bind");
		exit(0);
	}

	/* 把主动，变成被动*/
	if( (listen(fd, BACKLOG)) < 0)
	{
		perror("listen");
		exit(1);
	}
	printf("服务器加载成功\n");

	int newfd = -1;
	/* 阻塞连接*/
	if( (newfd = accept(fd , NULL, NULL)) < 0)
	{
		perror("accept");
		exit(1);
	}
	printf("连接成功\n");


#if 0
	/* 读写 */
	char buf[BUFSI] = {0};
	int ret = -1;

	while(1)
	{
		bzero(buf, BUFSI);
		do{	
			ret = read(newfd, buf, BUFSI-1);
			/* 遇到了中断，重复读 */
		}while(ret < 0 && errno == EINTR  );

		if(ret < 0)
		{	/* 读取失败 */
			perror("read");
			exit(1);
		}

		if(!ret)
		{
			// 服务器关闭了 
			printf("服务器已关闭\n");
			break;
		}
		printf("read data: %s\n", buf);
		
		/* 是否要退出了 */
		if(! strncasecmp(buf, QUIT_ST, sizeof(QUIT_ST)))
		{
			printf("服务器退出连接\n");
			break;
		}


	}

#else

	int ret = -1;
	char buf[BUFSI];

	while(1)
	{
		bzero(buf, BUFSI); /* 每次清空里面的数据 */
		do
		{
			ret = read(newfd, buf, BUFSI - 1 );
		}while(ret < 0 && errno == EINTR);

		if(ret < 0)
		{
			perror("read");
			exit(0);
		}
		if(!ret)
		{
			break;
		}
		//打印数据
		printf("read = data: %s\n", buf);

		if( !strncasecmp(buf, QUIT_ST, strlen(QUIT_ST))) {  //用户输入了quit字符
			printf("Client is exiting!\n");
			break;
		}	

	}
#endif


	//关闭套接字
	close(newfd);
	close(fd);
	return 0;

}





























































